<?php

// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org 
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------

namespace app\admin\controller\management;


use app\admin\model\management\Store as StoreModel;
use app\admin\model\management\Lease as LeaseModel;
use app\admin\model\management\LeasePrice as LeasePriceModel;
use app\admin\service\TriggerService;
use app\common\constants\AdminConstant;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Request;
use think\facade\Db;
use app\admin\model\ManagementStoreBecome;
/**
 * Class Admin
 * @package app\admin\controller\system
 * @ControllerAnnotation(title="管理员管理")
 */
class Lease extends AdminController
{

    use \app\admin\traits\Curd;
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->store = new StoreModel();
        $this->model  =new LeaseModel();
        $this->lease_price  =new LeasePriceModel();
    }
    public function  getSpec($cate_id=1){
        $list=Db::name('spec')->where('cate_id',1)->order('sort asc')->select()->toArray();
        foreach ($list as $k => $v) {
            $item=Db::name('spec_item')->where('spec_id',$v['id'])->column('item');
            $list[$k]['content']=implode(',',$item);
        }
        return $list;
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model->where($where)->count();
            $list  = $this->model->order('id asc')->where($where)->page($page, $limit)->select();
       
            $data  = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="添加")
     */
    public function add($id = null)
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                // 'cate_id|cate_id'    => 'require|>:0',
            ];
            $this->validate($post, $rule);
            if($post['spec_type']=="more"){
                $data=$this->getData($post);
                 $post=$data['data'];
                 $post['lease_value']=$data['lease_value'];
            }
           
               Db::startTrans();
            try {
                $save = $this->model->save($post);
                Db::commit();
            } catch (\Exception $e) {
                $this->error($e->getMessage());
                Db::rollback();
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $specs=$this->getSpec();
        $this->assign([
            'id'=>$id,
            'specs'=>$specs
        ]);
        return $this->fetch();
    }
    //处理多规格数据
    public function getData($post){
        foreach ($post['skus'] as $k => $v) {
            $sku_val="";
            foreach (explode(',',$k) as $k1 => $v1) {
              
                 $sku_val.= "_". Db::name('spec')->where('a.cate_id',1)->whereIn('a.id',$post['specs'])->where('b.item',$v1)->alias('a')->join('spec_item b','a.id=b.spec_id')->value('b.id');     
            }       
            $sku_val=array_filter(explode('_',$sku_val));
            sort($sku_val);
            $lease_value[]=[
                            'price'          =>$v['price'],
                            'activity_price' =>$v['activity_price'],
                            'deposit'        =>$v['deposit'],
                            'sku'            =>$k,
                            'sku_val'        =>implode('_',$sku_val),
                            'day_time'       =>substr($k,0,strrpos($k,",")),
                        ];
                          
        }
        $post['price']=min(array_column($lease_value,'price'));
        $post['activity_price']=min(array_column($lease_value,'activity_price'));
        $post['deposit']=min(array_column($lease_value,'deposit'));
        $list['data']=$post;
        $list['lease_value']=$lease_value;
        return $list;
    }
    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit()
    {   
        $id  = Request::param('id');
        $row = $this->model->where('id',$id)->find();
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
           
            $rule = [];
            $this->validate($post, $rule);
          if($post['spec_type']=="more"){
                $data=$this->getData($post);
                $post=$data['data'];
                $post['lease_value']=$data['lease_value'];
            }
            
               Db::startTrans();
            try {
                $save = $row->save($post);
                Db::commit();
            } catch (\Exception $e) {
                $this->error($e->getMessage());
                Db::rollback();
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $specs=$this->getSpec();
        $this->assign([
            'row'=>$row,
            'specs'=>$specs
        ]);
       
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="删除")
     */
    public function delete($id)
    {  
    
        $row = $this->model->whereIn('id', $id)->select();
     
        $row->isEmpty() && $this->error('数据不存在');
        try {
            $save = $this->model->whereIn('id', $id)->delete();
       
            foreach ($row as $k => $v) {
                 $main_picture=$v['main_image']?explode('|',$v['main_image']):'';
                if($main_picture){
                    foreach ($main_picture as $main) {
                        del_image($main);
                    }
                }
                $detail_picture=$v['detail_image']?explode('|',$v['detail_image']):'';
                if($detail_picture){
                    foreach ($detail_picture as $detail) {
                        del_image($detail);
                    }
                }
                del_image($v['thumb']);
            }
            $this->lease_price->whereIn('lease_id', $id)->delete();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    /**
     * 
     * @NodeAnotation(title="属性修改")
     */
    public function modify()
    {
        $post = $this->request->post();
     
        $rule = [
            // 'cate_id|ID'    => 'require',
            'field|字段' => 'require',
            'value|值'  => 'require',
        ];
        $this->validate($post, $rule);
        // if (!in_array($post['field'], $this->allowModifyFields)) {
        //     $this->error('该字段不允许修改：' . $post['field']);
        // }
     
        $row = $this->model->where('id',$post['id'])->find();
        empty($row) && $this->error('数据不存在');
        try {
            $row->save([
                $post['field'] => $post['value'],
            ]);
        } catch (\Exception $e) {
            // $this->error($e->getMessage());
            $this->success('保存成功');
        }
        $this->success('保存成功');
    }
     /**
     * @NodeAnotation(title="日历价格设置")
     */
    public function price($id = null)
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                // 'cate_id|cate_id'    => 'require|>:0',
            ];
            $this->validate($post, $rule);
           
            // $dayDate=$post['dayDate'];
            $data=[];
            // foreach ($dayDate as $k => $v) {
            //     $temp=explode(',',$v);
            //     $data[]=[
            //         'price'         =>$temp[1],
            //         'create_time'   =>strtotime($temp[0]),
            //         'tree_ticket_id'=>$post['tree_ticket_id']
            //     ];
            // }
            $dayDate=$post['data'];
            foreach ($dayDate as $k => $v) {
                   $data[]=[
                        'price'         =>$v['price'],
                        'activity_price'  =>$v['activity_price'],
                        'stock'         =>$v['stock'],
                        'create_time'   =>strtotime($v['date']),
                        'tree_ticket_id'=>$post['tree_ticket_id']
                   ];
            }
             $price=min(array_column($data,'price'));
             $activity_price=min(array_column($data,'activity_price'));
            try {
                Db::name('ticket')->where('id',$post['tree_ticket_id'])->update(['price'=>$price,'activity_price'=>$activity_price]);
                $save =Db::name('ticket_price')->insertAll($data);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $priceData=Db::name('ticket_price')->where('tree_ticket_id',$id)->select()->toArray();
        foreach ($priceData as $k => $v) {
            $priceData[$k]['date']=date('Y-m-d',$v['create_time']);
        }
      
        $this->assign([
            'id'=>$id,
            'priceData'=>$priceData?json_encode($priceData):'',
        ]);
        return $this->fetch();
    }
   
}
